/* Copyright © 2010 LPRM
Universidade Federal do Espírito Santo - RNP-GT CWTools

This file is part of JoinUs!.

JoinUs! is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

JoinUs! is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License
along with JoinUs!. If not, see <http://www.gnu.org/licenses/>. */
package br.ufes.cwtools.joinus.home.map;

import java.util.List;

import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import br.ufes.cwtools.joinus.R;
import br.ufes.cwtools.joinus.util.ServerCom;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;


public class AreaChooser extends MapActivity implements OnTouchListener{
	private static final int MENU_ZOOM_IN = 0;
	private static final int MENU_ZOOM_OUT = 1;
	
	private MapView mapView;
	private MapController mapc;
	private GeoPoint center;
	private GeoPoint tang;
	private boolean first = true;
	private long lastTouchTime = 0;
	
	@Override
	public void onCreate(Bundle b) {
		super.onCreate(b);

		mapView = new MapView(this, ServerCom.GOOGLE_MAPS_KEY);
		setContentView(mapView);
		mapView.setClickable(true);
		mapView.setOnTouchListener(this);

		mapc = mapView.getController();
		LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		Location loc = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		
		GeoPoint point = null;
		if (loc != null) {
			point = new GeoPoint(
					(int) Math.round(loc.getLatitude() * 1E6),
					(int) Math.round(loc.getLongitude() * 1E6));
			mapc.setZoom(7);
		} else {
			Log.d("AreaChooser","GPS inativo.");
			point = new GeoPoint(-12211180,-53525395); // Centro do Brasil
			mapc.setZoom(5);
		}
		mapc.setCenter(point);
	}
	
	public boolean onCreateOptionsMenu(Menu menu) {
	    menu.add(0, MENU_ZOOM_IN, 0, "Zoom +");
	    menu.add(0, MENU_ZOOM_OUT, 0, "Zoom -");
	    return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		MapController map = mapView.getController();
	    switch (item.getItemId()) {
	    case MENU_ZOOM_IN:
	        map.zoomIn();
	        return false;
	    case MENU_ZOOM_OUT:
	    	map.zoomOut();
	        return false;
	    }
	    return false;
	}
	
	public void setLocation(double x, double y, Location l, MapView map) {
		double latSpan = map.getLatitudeSpan() / 1.0E6;
		double lngSpan = map.getLongitudeSpan() / 1.0E6;
		GeoPoint center = map.getMapCenter();
		
		double xPcnt = x / ((double) map.getWidth());
		double yPcnt = y / ((double) map.getHeight());
		
		double lat0 = center.getLatitudeE6() / 1.0E6 + (latSpan / 2.0);
		double lng0 = center.getLongitudeE6() / 1.0E6 - (lngSpan / 2.0);
		
		double lat = lat0 - (yPcnt * latSpan);
		double lng = lng0 + (xPcnt * lngSpan);
		l.setLatitude(lat);
		l.setLongitude(lng);
	}

	public boolean onTouch(View view, MotionEvent event) {
		int action = event.getAction();
		if (action == MotionEvent.ACTION_DOWN) {
			long thisTime = System.currentTimeMillis();
			if (thisTime - lastTouchTime < 250) {
					GeoPoint p = mapView.getProjection().fromPixels(
							(int) Math.round(event.getX()), (int) Math.round(event.getY()));
					List<Overlay> mapOverlays = mapView.getOverlays();
					ItemOverlay itemizedoverlay = new ItemOverlay(getResources().getDrawable(R.drawable.bluedot));
					OverlayItem overlayitem = new OverlayItem(p, "", "");
					itemizedoverlay.addOverlay(overlayitem);
					mapOverlays.add(itemizedoverlay);
					if (first) {
						Log.d("AreaChooser", "First point selected: "+p.getLatitudeE6()+", "+p.getLongitudeE6());
						center = p;
						
					} else {
						Log.d("AreaChooser", "Second point selected: "+p.getLatitudeE6()+", "+p.getLongitudeE6());
						tang = p;

						Bundle extras = new Bundle();
						extras.putInt("lat1", center.getLatitudeE6());
						extras.putInt("lon1", center.getLongitudeE6());
						extras.putInt("lat2", tang.getLatitudeE6());
						extras.putInt("lon2", tang.getLongitudeE6());
						Intent intent = new Intent();
						intent.putExtras(extras);
						setResult(MapActivity.RESULT_OK, intent);
						
						finish();
					}
					first = !first;
					return true;
			}
			lastTouchTime = thisTime;
		}
		return false;
	}
	
	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}
}